/*
 * i2c.c
 *
 *  Created on: Apr 18, 2013
 *      Author: Vincent
 */

#include "support_common.h" /* include peripheral declarations and more */
#include <stdio.h>
#include "i2c.h"
#include "dtim.h"
#include "pit0.h"
#include "ledmat.h"


#define I2C_READ 0x01 //The Read/Write bit is set for a Read operation.
#define I2C_WRITE 0x00 //The Read/Write bit is cleared for a Write operation.

int dummy;
int counters = 0; // test
	
void i2c_acquire_bus()
{
	counters++;
	while ((MCF_I2C0_I2SR & 0x20) == 0x20)
	{
		
	}
}

void i2c_init()
{	
	MCF_GPIO_PASPAR |= 0x05; //sets port AS pins 0,1 as the primary I2C Function.
	MCF_I2C0_I2ADR |= (0x08 << 1); // slave address
	MCF_I2C0_I2FDR = 0x3A; //Divider = 896??
	i2c_reset();
	if ((MCF_I2C0_I2SR & 0x20) == 0x20)
	{
		MCF_I2C0_I2CR &= 0x00;
		MCF_I2C0_I2CR |= 0xA0; 
		dummy = MCF_I2C0_I2DR;
		MCF_I2C0_I2SR &= 0x00;                     
		MCF_I2C0_I2CR &= 0x00;
		MCF_I2C0_I2CR |= 0x80;
	}
	

}

void i2c_reset()
{
	
	MCF_I2C0_I2CR = 0x80;
		
}

void i2c_rx (int addr, int count, int data[])
{
	i2c_acquire_bus();
	i2c_tx_addr(addr, I2C_READ);
	MCF_I2C0_I2CR &= ~(0x10);
	MCF_I2C0_I2CR &= ~(0x08);
	dummy = i2c_rx_byte();
	for (int i =0; i<(count -1); i++)
	{
		data[i] = i2c_rx_byte();
	}
	MCF_I2C0_I2CR |= 0x08;
	data[count -1] = i2c_rx_byte();
	i2c_rxtx_end();

}

int i2c_rx_byte()
{
	uint8 byte = MCF_I2C0_I2DR;
	while (!i2c_tx_complete())
	{
		
	}
	MCF_I2C0_I2SR &= ~(0x2);
	dtim0_delay();
	return byte;
}

void i2c_rxtx_end() 
{
	MCF_I2C0_I2CR &= ~(0x20);
	i2c_reset();
}

void i2c_tx(int addr, int count, int data[])
{
	i2c_acquire_bus();
	i2c_tx_addr(addr, I2C_WRITE);
	for (int i =0; i<= (count -1); i++)
		{
			i2c_tx_byte(data[i]);
		}

	i2c_rxtx_end();

}

void i2c_tx_addr(int addr,int rw) 
{
	int trans = 0x00;
	MCF_I2C0_I2CR |= 0x10;
	MCF_I2C0_I2CR |= 0x20;
	
	
	trans = (addr << 1); // shouldn't be a problem if addr is less than/equal to 16 bits
	trans |= rw;
	i2c_tx_byte(trans);
}

void i2c_tx_byte(int byte)
{
	int_inhibit_all();
	MCF_I2C0_I2DR = (unsigned char) byte; //?
	while (!i2c_tx_complete())
		{
		
		}
	MCF_I2C0_I2SR &= ~(0x02);
	int_uninhibit_all();
	dtim0_delay();
}

int i2c_tx_complete()
{
	if ((MCF_I2C0_I2SR & 0x02) == 0x02) // teste
	{	
		return 1;
	}
	else 
		return 0;
}
